var global_userid = -1;
function getUrlParam(key, defaultValue) {
    var pageUrl = window.location.search.substring(1);
    var pairs = pageUrl.split('&');
    for (var i = 0; i < pairs.length; i++) {
        var keyAndValue = pairs[i].split('=');
        if (keyAndValue[0] === key) {
            return keyAndValue[1];
        }
    }
    return defaultValue;
}

function mythGetRequest(params) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', params, true);
    xhr.onload = function (e) {
        //return xhr.response;
        var DataSource = JSON.parse(xhr.response);
        return DataSource;
    }
    xhr.send();
}

function login() {
    var txt_username = document.getElementsByName('loginname')[0];
    var txt_pass = document.getElementsByName('loginpsw')[0];
    var loginerror = document.getElementById("loginerror");
    var username = txt_username.value;
    var password = txt_pass.value;
    console.log('login:' + username + ',' + password);

    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'login?username=' + username + "&password=" + password, true);
    xhr.onload = function (e) {
        var DataSource = JSON.parse(xhr.response);
        if (DataSource.result == true) {
            console.log('login success!');
            self.location = 'table.html';
        } else {
            loginerror.innerHTML = '登录失败，密码错误';
            //alert('登录失败');
            console.log('login failed!');
        }
    }
    xhr.send();
}
function refreshList() {
    var td = document.getElementById("tablename");
    var tr = document.getElementById('tabletr');
    if (tr) {
        td.removeChild(tr);
    }
}
function addNewList(num, client) {
    //console.log('Add New list' + client);
    console.log('ADD new List:' + client.out);
    var td = document.getElementById("tablename");
    var tr = document.createElement('tr');
    tr.setAttribute('id','tabletr');
    td.appendChild(tr);
    var numbertd = document.createElement('td');
    numbertd.setAttribute("id", num);
    numbertd.innerHTML = num;
    tr.appendChild(numbertd);

    var hostname = document.createElement('td');
    hostname.setAttribute("id", client.hostname);
    hostname.innerHTML = client.hostname;
    tr.appendChild(hostname);

    var usernametd = document.createElement('td');
    var usernameinput = document.createElement('input');
    usernameinput.setAttribute("id", 'username_' + client.out);
    usernameinput.setAttribute("name", 'inputusername:' + client.out);
    usernameinput.setAttribute("type", 'text');
    usernameinput.setAttribute("value", client.username);
    usernameinput.setAttribute("class", 'table--input');
    //usernameinput.innerHTML = client.username;
    usernametd.appendChild(usernameinput);
    tr.appendChild(usernametd);

    var passwordtd = document.createElement('td');
    var passwordinput = document.createElement('input');
    passwordinput.setAttribute("id", 'password_' + client.out);
    passwordinput.setAttribute("name", 'inputpassword_' + client.out);
    passwordinput.setAttribute("value", client.password);
    passwordinput.setAttribute("type", 'text');
    passwordinput.setAttribute("class", 'table--input');
    //passwordinput.innerHTML = client.password;
    passwordtd.appendChild(passwordinput);
    tr.appendChild(passwordtd);

    var nametd = document.createElement('td');
    var nameinput = document.createElement('input');
    nameinput.setAttribute("id", 'name_' + client.out);
    nameinput.setAttribute("name", 'inputname_' + client.out);
    nameinput.setAttribute("value", client.name);
    nameinput.setAttribute("type", 'text');
    nameinput.setAttribute("class", 'table--input');
    //nameinput.innerHTML = client.name;
    nametd.appendChild(nameinput);
    tr.appendChild(nametd);

    var speed = document.createElement('td');
    speed.setAttribute("id", "id_speed_" + client.out);
    speed.setAttribute("name", "speed_" + client.out);
    speed.innerHTML = 0;
    tr.appendChild(speed);
}
var _lastsearch;
var _userid = 0;

function post(URL, PARAMS) {
    var temp = document.createElement("form");
    temp.action = URL;
    temp.method = "post";
    temp.style.display = "none";
    for (var x in PARAMS) {
        var opt = document.createElement("textarea");
        opt.name = x;
        opt.value = PARAMS[x];
        // alert(opt.name)        
        temp.appendChild(opt);
    }
    document.body.appendChild(temp);
    temp.submit();
    return temp;
}

function table_onSearch() {
    var xhr = new XMLHttpRequest();
    console.log('start search');
    xhr.open('GET', 'search', true);
    xhr.onload = function (e) {
        if (!xhr.response) {
            console.log('server not reply');
            return;
        }
        var DataSource = JSON.parse(xhr.response);
        if (!DataSource) {
            console.log('server not reply');
            //start search
        } else {
            refreshList();
            _lastsearch = DataSource;
            var num = 0;
            for (var p in _lastsearch) {
                addNewList(num, _lastsearch[p]);
                num++;
            }
        }
    }
    xhr.send();
}
function table_onSubmit() {
    if (!_lastsearch) {
        console.log('empty search');
    } else {
        var myarray = [];
        for (var p in _lastsearch) {
            var url = _lastsearch[p].out;
            var username = document.getElementById("username_" + url);
            var password = document.getElementById("password_" + url);
            var name = document.getElementById("name_" + url);
            _lastsearch[p].username = username.value;
            _lastsearch[p].password = password.value;
            _lastsearch[p].name = name.value;
            myarray.push(_lastsearch[p]);
        }
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'update?userid=' + global_userid + '&json=' + JSON.stringify(myarray), true);
        xhr.onload = function (e) {
            //console.log('ok');
        }
        xhr.send();

        alert('提交成功!');
    }
}
function table_onload() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'getid', true);
    xhr.onload = function (e) {
        console.log(xhr.response);
        var ret = JSON.parse(xhr.response);
        global_userid = ret.userid;
        if (global_userid <= 0) {
            alert('未登录');
            self.location = 'index.html';
        }
    }
    xhr.send();
    //start get list
    var listopr = new XMLHttpRequest();
    listopr.open('GET', 'list', true);
    listopr.onload = function (e) {
        if (!listopr.response) {
            console.log('no camera current,try to search');
            table_onSearch();
            return;
        }
        console.log(listopr.response);
        var DataSource = JSON.parse(listopr.response);
        if (DataSource.length > 0) {
            _lastsearch = DataSource;
            var num = 0;
            for (var p in _lastsearch) {
                addNewList(num, _lastsearch[p]);
                num++;
            }
        } else {
            console.log('no camera current,try to search');
            table_onSearch();
        }
    }
    listopr.send();
    setInterval(function () {
        if (global_userid > 0) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'status', true);
            xhr.onload = function (e) {
                if (!xhr.response)
                    return;
                var DataSource = JSON.parse(xhr.response);
                if (DataSource) {
                    for (var p in DataSource) {
                        var td = document.getElementById("id_speed_" + DataSource[p].url);
                        if (td) {
                            td.innerHTML = DataSource[p].speed + 'kb/s';
                        }
                    }
                }
            }
            xhr.send();
        }
    }, 1000);
}
